//
//  UserAccountViewModel.swift
//  WeiBo
//
//  Created by tusm on 2017/6/27.
//  Copyright © 2017年 GM. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    
    var account:UserAccount?
    
    static let shareUserAccount = UserAccountViewModel()
    
    /// 判断登录是否成功
    var isLogin:Bool{
        
        if account != nil && !isExpired{
            
            return true
            
        }
        
        return false
    }
    
    
    /// 判断账号是否过期
    var isExpired:Bool{
        
        //测试过期效果代码
        //account?.expires_date = NSDate(timeIntervalSinceNow: -3600)
        
        if account?.expires_date?.compare(NSDate() as Date) == ComparisonResult.orderedDescending{
            
            return false
            
        }
        
        return true
    }
    
    
    fileprivate var accountPaht:String{
        
      let  path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
        
        return (path as NSString).appendingPathComponent("account.plist")
        
    }
    
    private init() {
        
       account =  NSKeyedUnarchiver.unarchiveObject(withFile: accountPaht) as? UserAccount
        
        if isExpired{
            
            print("已过期")
            
            account = nil
        }
        
       //print(account as Any)
        
    }
}


// MARK: - 获取用户信息方法
extension UserAccountViewModel{
    
    
    /// 加载access_token
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - finished: 完成回调
    func loadAccessToken(code:String, finished:@escaping (_ isSuccessed:Bool)->()){
        
        NetworkTools.shareTools.loadAcceaaToken(code: code) { (result, error) in
            
            if error != nil{
                
                print("出错了")
                
                finished(false)
                
                return
            }
            
            print(result as Any)
            
            let account = UserAccount(dict: result as! [String:AnyObject])
            
            self.getAccount(account: account, finished: finished)
        }
        
        
    }
    
    ///取得用户信息并归档
    private func getAccount(account:UserAccount,finished:@escaping (_ isSuccessed:Bool)->()){
        
        NetworkTools.shareTools.loadUserInfo(accessToken: account.access_token!, uid: account.uid!) { (result, error) in
            
            if error != nil{
                print("加载出错了")
                finished(false)
                return
            }
            
            guard let dict = result as? [String:AnyObject] else{
                print("格式错误")
                
                finished(false)
                
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
      
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPaht)
            
            finished(true)
            
        }
        
    }

}
